package com.dfxy.blog.panel;

import com.dfxy.blog.dao.ApproveDao;
import com.dfxy.blog.dao.BlogDao;
import com.dfxy.blog.entity.Approve;
import com.dfxy.blog.entity.Blog;
import com.dfxy.blog.util.DBUtil;
import com.dfxy.blog.window.MainWindow;
import com.mysql.cj.util.StringUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.SQLException;

public class BlogPanel extends JPanel {

    private String userName;
    private String publisherName;
    private String blogContent;
    private String publishTime;
    private int approveCount = 0;
    private MainWindow mainWindow;

    private JTextArea textAreaBlogContent = new JTextArea();
    private JPanel panelSouth = new JPanel();
    private JPanel panelSouthCenter = new JPanel();
    private JButton buttonApprove = new JButton();
    private JButton buttonDelete = new JButton("删除");
    private JButton buttonCancelApprove = new JButton("取消赞");
    private JLabel labelApproveUsernames = new JLabel();

    private Blog blog;

    public BlogPanel(String userName,
                     String publisherName,
                     String blogContent,
                     String publishTime,
                     MainWindow mainWindow) {

        this.userName = userName;
        this.publisherName = publisherName;
        this.blogContent = blogContent;
        this.publishTime = publishTime;
        this.mainWindow = mainWindow;

        init();
    }

    private void init() {
        this.setLayout(new BorderLayout());
        textAreaBlogContent.setText(publisherName + "(" + publishTime + "):" + blogContent);
        // textAreaBlogContent.setEnabled(false);
        textAreaBlogContent.setEditable(false);
        this.add(textAreaBlogContent, BorderLayout.CENTER);

        buttonApprove.setText("赞|" + approveCount);
        buttonApprove.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                BlogDao blogDao = new BlogDao();
                ApproveDao approveDao = new ApproveDao();
                try {
                    Connection con = DBUtil.getConnection();

                    // 更新blog表的approve_count
                    Blog apprvoeResult = blogDao.approve(con, blog);
                    // 点赞记录存入approve表
                    approveDao.approve(con, new Approve(userName, blog.getId()));
                    // 操作1 : 直接更改点赞用户列表
                    // apprvoeResult.getApproveUsernameSet().add(userName);
                    // 操作2 : 从数据库中更新点赞用户列表
                    apprvoeResult.setApproveUsernameSet(
                            approveDao.approveUsernameSet(con, apprvoeResult.getId()));

                    setBlog(apprvoeResult);

                    DBUtil.closeConnection(con);

                    // 刷新mainWindow中的点赞列表
                    mainWindow.refreshApproveIdSet();
                    // 点赞后禁止再赞
                    buttonApprove.setEnabled(false);
                    buttonCancelApprove.setEnabled(true);
                } catch (ClassNotFoundException ex) {
                    throw new RuntimeException(ex);
                } catch (SQLException ex) {
                    throw new RuntimeException(ex);
                }
            }
        });

        buttonCancelApprove.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                ApproveDao approveDao = new ApproveDao();
                BlogDao blogDao = new BlogDao();
                try {
                    // 创建mysql连接
                    Connection con = DBUtil.getConnection();
                    // 删除点赞记录
                    approveDao.delete(con, new Approve(userName, blog.getId()));
                    // 更新点赞数
                    blog = blogDao.refreshApproveCount(con, blog);
                    buttonApprove.setText("赞|" + blog.getApproveCount());

                    blog.setApproveUsernameSet(approveDao.approveUsernameSet(con, blog.getId()));
                    setBlog(blog);

                    // 关闭mysql链接
                    DBUtil.closeConnection(con);

                    mainWindow.refreshApproveIdSet();
                    buttonCancelApprove.setEnabled(false);
                    buttonApprove.setEnabled(true);

                } catch (ClassNotFoundException ex) {
                    throw new RuntimeException(ex);
                } catch (SQLException ex) {
                    throw new RuntimeException(ex);
                }

            }
        });

        buttonDelete.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                BlogDao blogDao = new BlogDao();
                try {
                    Connection con = DBUtil.getConnection();

                    Blog deleteResultBLog = blogDao.delete(con, blog);
                    if (deleteResultBLog == null) {
                        JOptionPane.showMessageDialog(textAreaBlogContent, "删除失败");
                    } else {
                        JOptionPane.showMessageDialog(textAreaBlogContent, "删除成功");

                        java.util.List<Blog> blogList = blogDao.blogList(con);
                        mainWindow.updateBlogList(blogList);
                    }

                    DBUtil.closeConnection(con);
                } catch (ClassNotFoundException ex) {
                    throw new RuntimeException(ex);
                } catch (SQLException ex) {
                    throw new RuntimeException(ex);
                }
            }
        });

        panelSouth.setLayout(new BorderLayout());
        panelSouth.add(buttonApprove, BorderLayout.EAST);
        panelSouth.add(buttonDelete, BorderLayout.WEST);

        panelSouthCenter.setLayout(new BorderLayout());
        panelSouthCenter.add(buttonCancelApprove, BorderLayout.EAST);

        labelApproveUsernames.setText("                    ❤   小刚,小红");
        panelSouthCenter.add(labelApproveUsernames, BorderLayout.CENTER);

        panelSouth.add(panelSouthCenter, BorderLayout.CENTER);

        this.add(panelSouth, BorderLayout.SOUTH);

        // 【删除】{                        {【取消赞】}}【点赞】
    }

    public void update(String publisherName, String blogContent, String publishTime) {
        this.publisherName = publisherName;
        this.blogContent = blogContent;
        this.publishTime = publishTime;
        textAreaBlogContent.setText(publisherName + "(" + publishTime + "):" + blogContent);
    }

    public void clear() {
        this.publisherName = null;
        this.blogContent = null;
        this.publishTime = null;
        textAreaBlogContent.setText("");
        buttonApprove.setEnabled(false);
        buttonCancelApprove.setEnabled(false);
    }

    public void setPublisherName(String publisherName) {
        this.publisherName = publisherName;
    }

    public void setBlogContent(String blogContent) {
        this.blogContent = blogContent;
    }

    public void setPublishTime(String publishTime) {
        this.publishTime = publishTime;
    }

    public void setBlog(Blog blog) {
        this.blog = blog;

        if (blog == null) {
            buttonApprove.setText("赞|0");
        } else {
            buttonApprove.setText("赞|" + blog.getApproveCount());
            buttonApprove.setEnabled(true);
            buttonCancelApprove.setEnabled(true);
        }

        buttonDelete.setEnabled(userName != null && userName.equals(publisherName));

        if (blog == null
                || blog.getApproveUsernameSet() == null
                || blog.getApproveUsernameSet().isEmpty()
        ) {
            labelApproveUsernames.setText("");
        } else {
            String approveUsernamesString = "                           ❤   ";
            String stringTemp = "";
            for (String name : blog.getApproveUsernameSet()) {
                if (StringUtils.isEmptyOrWhitespaceOnly(stringTemp)) {
                    stringTemp = name;
                } else {
                    stringTemp += "," + name;
                }
            }
            approveUsernamesString += stringTemp;

            labelApproveUsernames.setText(approveUsernamesString);
        }
    }

    public void setBlog(Blog blog, boolean hasApproved) {
        setBlog(blog);

        if (hasApproved) {
            buttonApprove.setEnabled(false);
        } else {
            buttonCancelApprove.setEnabled(false);
        }
    }

    public JButton getButtonApprove() {
        return buttonApprove;
    }

    public JButton getButtonCancelApprove() {
        return buttonCancelApprove;
    }
}
